/*!
* AudioElement.js
* HTML5 <audio> shim and player
*
* Creates a JavaScript object that mimics HTML5 MediaElement API.
*
*/
// Namespace
var mejs = mejs || {};

// Version number
mejs.version = '2.13.0'; 


// Player number
mejs.meIndex = 0;

// Media types accepted by plugins
mejs.plugins = {
	flash: [
		{version: [9,0,124], types: ['audio/mp3','audio/mpeg']}
	]
};

/*
Utility methods
*/
mejs.Utility = {
	encodeUrl: function(url) {
		return encodeURIComponent(url);
	},
	escapeHTML: function(s) {
		return s.toString().split('&').join('&amp;').split('<').join('&lt;').split('"').join('&quot;');
	},
	absolutiseUrl: function(url) {
		var el = document.createElement('div');
		el.innerHTML = '<a href="' + this.escapeHTML(url) + '">x</a>';
		return el.firstChild.href;
	},
	getScriptPath: function(scriptNames) {
		var
			i = 0,
			j,
			codePath = '',
			testname = '',
			slashPos,
			filenamePos,
			scriptUrl,
			scriptPath,			
			scriptFilename,
			scripts = document.getElementsByTagName('script'),
			il = scripts.length,
			jl = scriptNames.length;
			
		// Go through all <script> tags
		for (; i < il; i++) {
			scriptUrl = scripts[i].src;
			slashPos = scriptUrl.lastIndexOf('/');
			if (slashPos > -1) {
				scriptFilename = scriptUrl.substring(slashPos + 1);
				scriptPath = scriptUrl.substring(0, slashPos + 1);
			} else {
				scriptFilename = scriptUrl;
				scriptPath = '';			
			}
			
			// See if any <script> tags have a file name that matches
			for (j = 0; j < jl; j++) {
				testname = scriptNames[j];
				filenamePos = scriptFilename.indexOf(testname);
				if (filenamePos > -1) {
					codePath = scriptPath;
					break;
				}
			}
			
			// If we found a path, then break and return it
			if (codePath !== '') {
				break;
			}
		}
		
		// Send the best path back
		return codePath;
	},
	secondsToTimeCode: function(time, forceHours, showFrameCount, fps) {
		//add framecount
		if (typeof showFrameCount == 'undefined') {
		    showFrameCount=false;
		} else if(typeof fps == 'undefined') {
		    fps = 25;
		}
	
		var hours = Math.floor(time / 3600) % 24,
			minutes = Math.floor(time / 60) % 60,
			seconds = Math.floor(time % 60),
			result = 
					( (forceHours || hours > 0) ? (hours < 10 ? '0' + hours : hours) + ':' : '')
						+ (minutes < 10 ? '0' + minutes : minutes) + ':'
						+ (seconds < 10 ? '0' + seconds : seconds);	
		return result;
	},
	convertSMPTEtoSeconds: function (SMPTE) {
		if (typeof SMPTE != 'string') 
			return false;

		SMPTE = SMPTE.replace(',', '.');
		
		var secs = 0,
			decimalLen = (SMPTE.indexOf('.') != -1) ? SMPTE.split('.')[1].length : 0,
			multiplier = 1;
		
		SMPTE = SMPTE.split(':').reverse();
		
		for (var i = 0; i < SMPTE.length; i++) {
			multiplier = 1;
			if (i > 0) {
				multiplier = Math.pow(60, i); 
			}
			secs += Number(SMPTE[i]) * multiplier;
		}
		return Number(secs.toFixed(decimalLen));
	},	
	
	removeSwf: function(id) {
		var obj = document.getElementById(id);
		if (obj && /object|embed/i.test(obj.nodeName)) {
			if (mejs.MediaFeatures.isIE) {
				obj.style.display = "none";
				(function(){
					if (obj.readyState == 4) {
						mejs.Utility.removeObjectInIE(id);
					} else {
						setTimeout(arguments.callee, 10);
					}
				})();
			} else {
				obj.parentNode.removeChild(obj);
			}
		}
	},
	removeObjectInIE: function(id) {
		var obj = document.getElementById(id);
		if (obj) {
			for (var i in obj) {
				if (typeof obj[i] == "function") {
					obj[i] = null;
				}
			}
			obj.parentNode.removeChild(obj);
		}		
	}
};


// Core detector, plugins are added below
mejs.PluginDetector = {

	// Main public function to test a plug version number PluginDetector.hasPluginVersion('flash',[9,0,125]);
	hasPluginVersion: function(plugin, v) {
		var pv = this.plugins[plugin];
		v[1] = v[1] || 0;
		v[2] = v[2] || 0;
		return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
	},

	// Cached values
	nav: window.navigator,
	ua: window.navigator.userAgent.toLowerCase(),

	// Stored version numbers
	plugins: [],

	// Runs detectPlugin() and stores the version number
	addPlugin: function(p, pluginName, mimeType, activeX, axDetect) {
		this.plugins[p] = this.detectPlugin(pluginName, mimeType, activeX, axDetect);
	},

	// Get the version number from the mimetype (all but IE) or ActiveX (IE)
	detectPlugin: function(pluginName, mimeType, activeX, axDetect) {

		var version = [0,0,0],
			description,
			i,
			ax;

		// Firefox, Webkit, Opera
		if (typeof(this.nav.plugins) != 'undefined' && typeof this.nav.plugins[pluginName] == 'object') {
			description = this.nav.plugins[pluginName].description;
			if (description && !(typeof this.nav.mimeTypes != 'undefined' && this.nav.mimeTypes[mimeType] && !this.nav.mimeTypes[mimeType].enabledPlugin)) {
				version = description.replace(pluginName, '').replace(/^\s+/,'').replace(/\sr/gi,'.').split('.');
				for (i=0; i<version.length; i++) {
					version[i] = parseInt(version[i].match(/\d+/), 10);
				}
			}
		// Internet Explorer / ActiveX
		} else if (typeof(window.ActiveXObject) != 'undefined') {
			try {
				ax = new ActiveXObject(activeX);
				if (ax) {
					version = axDetect(ax);
				}
			}
			catch (e) { }
		}
		return version;
	}
};

// Flash detection
mejs.PluginDetector.addPlugin('flash','Shockwave Flash','application/x-shockwave-flash','ShockwaveFlash.ShockwaveFlash', function(ax) {
	var version = [],
		d = ax.GetVariable("$version");
	if (d) {
		d = d.split(" ")[1].split(",");
		version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
	}
	return version;
});
mejs.MediaFeatures = {
	init: function() {
		var
			t = this,
			d = document,
			nav = mejs.PluginDetector.nav,
			ua = mejs.PluginDetector.ua.toLowerCase(),
			i,
			v,
			html5Elements = ['source','audio'];

		// Detect Browsers
		t.isiPad = (ua.match(/ipad/i) !== null);
		t.isiPhone = (ua.match(/iphone/i) !== null);
		t.isiOS = t.isiPhone || t.isiPad;
		t.isAndroid = (ua.match(/android/i) !== null);
		t.isOldAndroid = (ua.match(/android 2\.[12]/) !== null);
		t.isIE = (nav.appName.match(/microsoft/gi) !== null) || (ua.match(/trident/gi) !== null);
		t.isChrome = (ua.match(/chrome/gi) !== null);
                t.isChromium = (ua.match(/chromium/gi) !== null);
		t.isFirefox = (ua.match(/firefox/gi) !== null);
		t.isWebkit = (ua.match(/webkit/gi) !== null);
		t.isGecko = (ua.match(/gecko/gi) !== null) && !t.isWebkit;
		t.isOpera = (ua.match(/opera/gi) !== null);
		t.hasTouch = ('ontouchstart' in window);
		
		t.svg = !! document.createElementNS &&
				!! document.createElementNS('http://www.w3.org/2000/svg','svg').createSVGRect;

		// Create HTML5 media elements
		for (i=0; i<html5Elements.length; i++) {
			v = document.createElement(html5Elements[i]);
		}
		
		t.supportsMediaTag = (typeof v.canPlayType !== 'undefined' || t.isOldAndroid);

		// Fix for IE9 on Windows 7N / Windows 7KN (Media Player not installed)
		try{
			v.canPlayType("audio/mp3");
		}catch(e){
			t.supportsMediaTag = false;
		}
	}
};
mejs.MediaFeatures.init();

/*
Extension methods to <audio> object
*/
mejs.HtmlMediaElement = {
	pluginType: 'native',

	setCurrentTime: function (time) {
		this.currentTime = time;
	},

	setMuted: function (muted) {
		this.muted = muted;
	},

	setVolume: function (volume) {
		this.volume = volume;
	},

	// For parity with the plugin versions
	stop: function () {
		this.pause();
	},

	// This can be a url string or an array.
	setSrc: function (url) {
		
		// Fix for IE9 which can't set .src when there are <source> elements.
		var 
			existingSources = this.getElementsByTagName('source');
		while (existingSources.length > 0){
			this.removeChild(existingSources[0]);
		}
	
		if (typeof url == 'string') {
			this.src = url;
		} else {
			var i, media;

			for (i=0; i<url.length; i++) {
				media = url[i];
				if (this.canPlayType(media.type)) {
					this.src = media.src;
					break;
				}
			}
		}
	},
};

/*
Mimics the <audio> element by calling Flash's External Interface.
*/
mejs.PluginMediaElement = function (pluginid, pluginType, mediaUrl) {
	this.id = pluginid;
	this.pluginType = pluginType;
	this.src = mediaUrl;
	this.events = {};
	this.attributes = {};
};

// JavaScript values and ExternalInterface methods that match HTML5 audio properties methods
mejs.PluginMediaElement.prototype = {

	// Special
	pluginElement: null,
	pluginType: '',

	// Not currently implemented
	playbackRate: -1,
	defaultPlaybackRate: -1,
	seekable: [],
	played: [],

	// HTML5 read-only properties
	paused: true,
	ended: false,
	seeking: false,
	duration: 0,
	error: null,
	tagName: '',

	// HTML5 get/set properties, but only set (updated by event handlers)
	muted: false,
	volume: 1,
	currentTime: 0,

	// HTML5 methods
	play: function () {
		if (this.pluginApi != null) {
			this.pluginApi.playMedia();
			
			this.paused = false;
		}
	},
	load: function () {
		if (this.pluginApi != null) {
			this.pluginApi.loadMedia();
			
			this.paused = false;
		}
	},
	pause: function () {
		if (this.pluginApi != null) {
			this.pluginApi.pauseMedia();
			
			this.paused = true;
		}
	},
	stop: function () {
		if (this.pluginApi != null) {
			this.pluginApi.stopMedia();
	
			this.paused = true;
		}
	},
	canPlayType: function(type) {
		var i,
			j,
			pluginInfo,
			pluginVersions = mejs.plugins[this.pluginType];

		for (i=0; i<pluginVersions.length; i++) {
			pluginInfo = pluginVersions[i];

			// test if user has the correct plugin version
			if (mejs.PluginDetector.hasPluginVersion(this.pluginType, pluginInfo.version)) {

				// test for plugin playback types
				for (j=0; j<pluginInfo.types.length; j++) {
					// find plugin that can play the type
					if (type == pluginInfo.types[j]) {
						return 'probably';
					}
				}
			}
		}

		return '';
	},

	// Custom methods since not all JavaScript implementations support get/set

	// This can be a url string or an array.
        setSrc: function (url) {
		if (typeof url == 'string') {
			this.pluginApi.setSrc(mejs.Utility.absolutiseUrl(url));
			this.src = mejs.Utility.absolutiseUrl(url);
		} else {
			var i, media;

			for (i=0; i<url.length; i++) {
				media = url[i];
				if (this.canPlayType(media.type)) {
					this.pluginApi.setSrc(mejs.Utility.absolutiseUrl(media.src));
					this.src = mejs.Utility.absolutiseUrl(url);
					break;
				}
			}
		}

	},
	setCurrentTime: function (time) {
		if (this.pluginApi != null) {
			this.pluginApi.setCurrentTime(time);
                        this.currentTime = time;
		}
	},
	setVolume: function (volume) {
		if (this.pluginApi != null) {
			this.pluginApi.setVolume(volume);

			this.volume = volume;
		}
	},
	setMuted: function (muted) {
		if (this.pluginApi != null) {
			this.pluginApi.setMuted(muted);

			this.muted = muted;
		}
	},	

	// Fake events
	addEventListener: function (eventName, callback, bubble) {
		this.events[eventName] = this.events[eventName] || [];
		this.events[eventName].push(callback);
	},

	removeEventListener: function (eventName, callback) {
		if (!eventName) { this.events = {}; return true; }
		var callbacks = this.events[eventName];
		if (!callbacks) return true;
		if (!callback) { this.events[eventName] = []; return true; }
		for (i = 0; i < callbacks.length; i++) {
			if (callbacks[i] === callback) {
				this.events[eventName].splice(i, 1);
				return true;
			}
		}
		return false;
	},

	dispatchEvent: function (eventName) {
		var i,
			args,
			callbacks = this.events[eventName];

		if (callbacks) {
			args = Array.prototype.slice.call(arguments, 1);
			for (i = 0; i < callbacks.length; i++) {
				callbacks[i].apply(null, args);
			}
		}
	},
	
	// Fake DOM attribute methods
	hasAttribute: function(name){
		return (name in this.attributes);  
	},

	removeAttribute: function(name){
		delete this.attributes[name];
	},

	getAttribute: function(name){
		if (this.hasAttribute(name)) {
			return this.attributes[name];
		}
		return '';
	},

	setAttribute: function(name, value){
		this.attributes[name] = value;
	},

	remove: function() {
		mejs.Utility.removeSwf(this.pluginElement.id);
		mejs.MediaPluginBridge.unregisterPluginElement(this.pluginElement.id);
	}
};

// Handles calls from Flash and reports them as native <audio> events and properties
mejs.MediaPluginBridge = {

	pluginMediaElements:{},
	htmlMediaElements:{},

	registerPluginElement: function (id, pluginMediaElement, htmlMediaElement) {
		this.pluginMediaElements[id] = pluginMediaElement;
		this.htmlMediaElements[id] = htmlMediaElement;
	},

	unregisterPluginElement: function (id) {
		delete this.pluginMediaElements[id];
		delete this.htmlMediaElements[id];
	},

	// When Flash is ready, it calls out to this method
	initPlugin: function (id) {

		var pluginMediaElement = this.pluginMediaElements[id],
			htmlMediaElement = this.htmlMediaElements[id];

		if (pluginMediaElement) {
			// Find the javascript bridge
			switch (pluginMediaElement.pluginType) {
				case "flash":
					pluginMediaElement.pluginElement = pluginMediaElement.pluginApi = document.getElementById(id);
					break;
			}
	
			if (pluginMediaElement.pluginApi != null && pluginMediaElement.success) {
				pluginMediaElement.success(pluginMediaElement, htmlMediaElement);
			}
		}
	},

	// Receives events from Flash and sends them out as HTML5 media events
	fireEvent: function (id, eventName, values) {

		var
			e,
			i,
			bufferedTime,
			pluginMediaElement = this.pluginMediaElements[id];

		if(!pluginMediaElement){
            return;
        }
        
		// Fake event object to mimic real HTML media event.
		e = {
			type: eventName,
			target: pluginMediaElement
		};

		// Attach all values to element and event object
		for (i in values) {
			pluginMediaElement[i] = values[i];
			e[i] = values[i];
		}

		// Fake the newer W3C buffered TimeRange
		bufferedTime = values.bufferedTime || 0;

		e.target.buffered = e.buffered = {
			start: function(index) {
				return 0;
			},
			end: function (index) {
				return bufferedTime;
			},
			length: 1
		};

		pluginMediaElement.dispatchEvent(e.type, e);
	}
};

/*
Default options
*/
mejs.MediaElementDefaults = {
	// allows testing on HTML5, flash
	// auto: attempts to detect what the browser can do
	// native: forces HTML5 playback
	// shim: disallows HTML5, will attempt Flash
	// none: forces fallback view
	mode: 'auto',
	// Remove or reorder to change plugin priority and availability
	plugins: ['flash'],
	// Overrides the type specified, useful for dynamic instantiation
	type: '',
	// Path to Flash plugin
	pluginPath: mejs.Utility.getScriptPath(['audioelement.js','audioelement-and-player.js']),
	// Name of flash file
	flashName: 'flashmediaelement.swf',
	// additional plugin variables in 'key=value' form
	pluginVars: [],	
	// Rate in ms for Flash to fire the timeupdate event
	timerRate: 500,
	// Initial volume for player
	startVolume: 1.0,
        // Error message if source cannot be played
        customError: "Your browser does not support audio playback.",
                
	success: function () { },
	error: function () { }
};

/*
Determines if a browser supports the <audio> element
and returns either the native element or a Flash version that
mimics HTML5 MediaElement.
*/
mejs.MediaElement = function (el, o) {
	return mejs.HtmlMediaElementShim.create(el,o);
};

mejs.HtmlMediaElementShim = {

	create: function(el, o) {
		var
			options = mejs.MediaElementDefaults,
			htmlMediaElement = (typeof(el) == 'string') ? document.getElementById(el) : el,
			tagName = htmlMediaElement.tagName.toLowerCase(),
			isMediaTag = tagName === 'audio',
			src = (isMediaTag) ? htmlMediaElement.getAttribute('src') : htmlMediaElement.getAttribute('href'),
			autoplay =  htmlMediaElement.getAttribute('autoplay'),
			preload =  htmlMediaElement.getAttribute('preload'),
			controls =  htmlMediaElement.getAttribute('controls'),
			playback,
			prop;

		// Extend options
		for (prop in o) {
			options[prop] = o[prop];
		}

		// Clean up attributes
		src = 		(typeof src == 'undefined' 	|| src === null || src == '') ? null : src;		
		preload = 	(typeof preload == 'undefined' 	|| preload === null || preload === 'false') ? 'none' : preload;
		autoplay = 	!(typeof autoplay == 'undefined' || autoplay === null || autoplay === 'false');
		controls = 	!(typeof controls == 'undefined' || controls === null || controls === 'false');

		// Test for HTML5 capabilities
		playback = this.determinePlayback(htmlMediaElement, options, mejs.MediaFeatures.supportsMediaTag, isMediaTag, src);
		playback.url = (playback.url !== null) ? mejs.Utility.absolutiseUrl(playback.url) : '';

		if (playback.method == 'native') {
			// Second fix for android
			if (mejs.MediaFeatures.isOldAndroid) {
				htmlMediaElement.src = playback.url;
				htmlMediaElement.addEventListener('click', function() {
					htmlMediaElement.play();
				}, false);
			}
		
			// Add methods to native HTMLMediaElement
			return this.updateNative(playback, options, autoplay, preload);
		} else if (playback.method !== '') {
			// Create plugin to mimic HTMLMediaElement
			return this.createPlugin( playback,  options, autoplay, preload, controls);
		} else {
			// No HTML5.
			this.createErrorMessage( playback, options );
			
			return this;
		}
	},
	
	determinePlayback: function(htmlMediaElement, options, supportsMediaTag, isMediaTag, src) {
		var
			mediaFiles = [],
			i,
			j,
			k,
			l,
			n,
			type,
			result = { method: '', url: '', htmlMediaElement: htmlMediaElement },
			pluginName,
			pluginVersions,
			pluginInfo,
			dummy,
			media;
			
		// STEP 1: Get URL and type from <source src>

		// Supplied type overrides <source type>
		if (typeof options.type != 'undefined' && options.type !== '') {
			
			// Accept either string or array of types
			if (typeof options.type == 'string') {
				mediaFiles.push({type:options.type, url:src});
			} else {
				
				for (i=0; i<options.type.length; i++) {
					mediaFiles.push({type:options.type[i], url:src});
				}
			}

		// Test for src attribute first
		} else if (src !== null) {
			type = this.formatType(src, htmlMediaElement.getAttribute('type'));
			mediaFiles.push({type:type, url:src});

		// Then test for <source> elements
		} else {
			for (i = 0; i < htmlMediaElement.childNodes.length; i++) {
				n = htmlMediaElement.childNodes[i];
				if (n.nodeType == 1 && n.tagName.toLowerCase() == 'source') {
					src = n.getAttribute('src');
					type = this.formatType(src, n.getAttribute('type'));
					media = n.getAttribute('media');

					if (!media || !window.matchMedia || (window.matchMedia && window.matchMedia(media).matches)) {
						mediaFiles.push({type:type, url:src});
					}
				}
			}
		}

		// STEP 2: Test for playback method
                
		// Test for native playback
		if (supportsMediaTag && (options.mode === 'auto' || options.mode === 'native')) {
						
			if (!isMediaTag) {

				// Create a real HTML5 Media Element 
				dummy = document.createElement('audio');			
				htmlMediaElement.parentNode.insertBefore(dummy, htmlMediaElement);
				htmlMediaElement.style.display = 'none';
				
				// Use this one from now on
				result.htmlMediaElement = htmlMediaElement = dummy;
			}
				
			for (i=0; i<mediaFiles.length; i++) {
				// Normal check
				if (htmlMediaElement.canPlayType(mediaFiles[i].type).replace(/no/, '') !== '') {
					result.method = 'native';
					result.url = mediaFiles[i].url;
					break;
				}
			}			
			
			if (result.method === 'native') {
				if (result.url !== null) {
					htmlMediaElement.src = result.url;
				}
			
				return result;
			}
		}

		// If native playback didn't work, then test plugins
		if (options.mode === 'auto' || options.mode === 'shim') {
			for (i=0; i<mediaFiles.length; i++) {
				type = mediaFiles[i].type;

				// Test all plugins
				for (j=0; j<options.plugins.length; j++) {

					pluginName = options.plugins[j];
			
					// Test version of plugin (for future features)
					pluginVersions = mejs.plugins[pluginName];				
					
					for (k=0; k<pluginVersions.length; k++) {
						pluginInfo = pluginVersions[k];
					
						// Test if user has the correct plugin version
						if (pluginInfo.version == null || 
							
							mejs.PluginDetector.hasPluginVersion(pluginName, pluginInfo.version)) {

							// Test for plugin playback types
							for (l=0; l<pluginInfo.types.length; l++) {
								// find plugin that can play the type
								if (type == pluginInfo.types[l]) {
									result.method = pluginName;
									result.url = mediaFiles[i].url;
									return result;
								}
							}
						}
					}
				}
			}
		}

		// What if there's nothing to play? just grab the first available
		if (result.method === '' && mediaFiles.length > 0) {
			result.url = mediaFiles[0].url;
		}

		return result;
	},

	formatType: function(url, type) {
                // only return the mime part of the type in case the attribute contains the codec.
                if (type && ~type.indexOf(';')) {
                        return type.substr(0, type.indexOf(';')); 
                } else {
                        return type;
                }
	},

	createErrorMessage: function(playback, options) {
		var 
			htmlMediaElement = playback.htmlMediaElement,
			errorContainer = document.createElement('div');
			
		errorContainer.className = 'me-cannotplay';

		try {
			errorContainer.style.width = htmlMediaElement.width + 'px';
			errorContainer.style.height = htmlMediaElement.height + 'px';
		} catch (e) {}

    if (options.customError) {
      errorContainer.innerHTML = options.customError;
    }
		htmlMediaElement.parentNode.insertBefore(errorContainer, htmlMediaElement);
		htmlMediaElement.style.display = 'none';

		options.error(htmlMediaElement);
	},

	createPlugin:function(playback, options, autoplay, preload, controls) {
		var 
			htmlMediaElement = playback.htmlMediaElement,
			width = 1,
			height = 1,
			pluginid = 'me_' + playback.method + '_' + (mejs.meIndex++),
			pluginMediaElement = new mejs.PluginMediaElement(pluginid, playback.method, playback.url),
			container = document.createElement('div'),
			specialIEContainer,
			node,
			initVars;

		// Copy tagName from html media element
		pluginMediaElement.tagName = htmlMediaElement.tagName;

		// Copy attributes from html media element to plugin media element
		for (var i = 0; i < htmlMediaElement.attributes.length; i++) {
			var attribute = htmlMediaElement.attributes[i];
			if (attribute.specified == true) {
				pluginMediaElement.setAttribute(attribute.name, attribute.value);
			}
		}

		// Check for placement inside a <p> tag (sometimes WYSIWYG editors do this)
		node = htmlMediaElement.parentNode;
		while (node !== null && node.tagName.toLowerCase() != 'body') {
			if (node.parentNode.tagName.toLowerCase() == 'p') {
				node.parentNode.parentNode.insertBefore(node, node.parentNode);
				break;
			}
			node = node.parentNode;
		}

		// Register plugin
		pluginMediaElement.success = options.success;
		mejs.MediaPluginBridge.registerPluginElement(pluginid, pluginMediaElement, htmlMediaElement);

		// Add container (must be added to DOM before inserting HTML for IE)
		container.className = 'me-plugin';
		container.id = pluginid + '_container';
		
		document.body.insertBefore(container, document.body.childNodes[0]);

		// Flash vars
		initVars = [
			'id=' + pluginid,
			'autoplay=' + ((autoplay) ? "true" : "false"),
			'preload=' + preload,
			'width=' + width,
			'startvolume=' + options.startVolume,
			'timerrate=' + options.timerRate,
			'height=' + height];

		if (playback.url !== null) {
			if (playback.method == 'flash') {
				initVars.push('file=' + mejs.Utility.encodeUrl(playback.url));
			} else {
				initVars.push('file=' + playback.url);
			}
		}
		if (options.enablePluginSmoothing) {
			initVars.push('smoothing=true');
		}
		if (controls) {
			initVars.push('controls=true');
		}
		if (options.pluginVars) {
			initVars = initVars.concat(options.pluginVars);
		}		

		switch (playback.method) {
			case 'flash':

				if (mejs.MediaFeatures.isIE) {
					specialIEContainer = document.createElement('div');
					container.appendChild(specialIEContainer);
					specialIEContainer.outerHTML =
'<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' +
'id="' + pluginid + '" width="' + width + '" height="' + height + '" class="mejs-shim">' +
'<param name="movie" value="' + options.pluginPath + options.flashName + '?x=' + (new Date()) + '" />' +
'<param name="flashvars" value="' + initVars.join('&amp;') + '" />' +
'<param name="quality" value="high" />' +
'<param name="bgcolor" value="#000000" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowScriptAccess" value="always" />' +
'</object>';

				} else {

					container.innerHTML =
'<embed id="' + pluginid + '" name="' + pluginid + '" ' +
'play="true" ' +
'loop="false" ' +
'quality="high" ' +
'bgcolor="#000000" ' +
'wmode="transparent" ' +
'allowScriptAccess="always" ' +
'type="application/x-shockwave-flash" pluginspage="//www.macromedia.com/go/getflashplayer" ' +
'src="' + options.pluginPath + options.flashName + '" ' +
'flashvars="' + initVars.join('&') + '" ' +
'width="' + width + '" ' +
'height="' + height + '" ' +
'class="mejs-shim"></embed>';
				}
				break;			
		}
		// Hide original element
		htmlMediaElement.style.display = 'none';

		// Prevent browser from autoplaying when using a plugin
		htmlMediaElement.removeAttribute('autoplay');
		
		return pluginMediaElement;
	},

	updateNative: function(playback, options, autoplay, preload) {
		
		var htmlMediaElement = playback.htmlMediaElement,
			m;
		
		
		// Add methods to audio object to bring it into parity with Flash Object
		for (m in mejs.HtmlMediaElement) {
			htmlMediaElement[m] = mejs.HtmlMediaElement[m];
		}

		// Fire success code
		options.success(htmlMediaElement, htmlMediaElement);
		
		return htmlMediaElement;
	}
};

window.mejs = mejs;
window.MediaElement = mejs.MediaElement;


/*!
 * AudioElementPlayer
 *
 * Creates a controller bar for HTML5 <audio> tags
 * using jQuery and AudioElement.js (HTML5 Flash wrapper)
 *
 */
if (typeof jQuery != 'undefined') {
	mejs.$ = jQuery;
} else if (typeof ender != 'undefined') {
	mejs.$ = ender;
}
(function ($) {

	// Default player values
	mejs.MepDefaults = {
            
		// Default if the user doesn't specify
		defaultWidth: 400,
		// Default if the user doesn't specify
		defaultHeight: 30,

		// Default amount to move back when back key is pressed
		defaultSeekBackwardInterval: function(player, media) {
                           return ((player.options.duration > 0) ? (player.options.duration * 0.05) : (media.duration * 0.05));
		},
                        
		// Default amount to move forward when forward key is pressed
		defaultSeekForwardInterval: function(player, media) {
			return ((player.options.duration > 0) ? (player.options.duration * 0.05) : (media.duration * 0.05));
		},

		// Width of audio player
		width: -1,
		// Height of audio player
		height: -1,
		// Initial volume when the player starts (overrided by user cookie)
		startVolume: 0.8,
		// Resize to media dimensions
		enableAutosize: true,
		// Forces the hour marker (##:00:00)
		alwaysShowHours: false,
		// Automatically calculate the width of the progress bar based on the sizes of other elements
		autosizeProgress : true,
		// Features
		features: ['playpause','current','progress','duration','volume', 'captioncustomiser'],

		// Turns keyboard support on and off for this instance
		enableKeyboard: true,

		// When this player starts, it will pause other players
		pauseOtherPlayers: true,

		// Array of keyboard actions
		keyActions: [
                                {
                                    keys: [
                                        32, // SPACE
                                        179 // GOOGLE play/pause button
                                    ],
                                    action: function(player, media)
                                    {
                                        if (media.paused || media.ended)
                                        {
                                            player.play();
                                        } 
                                        else 
                                        {
                                            player.pause();
                                        }
                                    }
				},
				{
                                    keys: [38], // UP
                                    action: function(player, media)
                                    {
                                        player.container.find('.mejs-volume-slider').css('display','block');

                                        var newVolume = Math.min(media.volume + 0.1, 1);
                                        media.setVolume(newVolume);
                                    }
				},
				{
                                    keys: [40], // DOWN
                                    action: function(player, media)
                                    {
                                        player.container.find('.mejs-volume-slider').css('display','block');

                                        var newVolume = Math.max(media.volume - 0.1, 0);
                                        media.setVolume(newVolume);
                                    }
				},
				{
                                    keys: [
                                                    37, // LEFT
                                                    227 // Google TV rewind
                                    ],
                                    action: function(player, media) {
                                                    if ((player.options.duration > 0) || (media.duration > 0)) {

                                                                    // 5%
                                                                    var newTime = Math.max(player.currentTime - player.options.defaultSeekBackwardInterval(player, media), 0);
                                                                    player.setCurrentTime(newTime);
                                                    }
                                    }
				},
				{
                                    keys: [
                                                    39, // RIGHT
                                                    228 // Google TV forward
                                    ],
                                    action: function(player, media) {
                                                    if ((player.options.duration > 0) || (media.duration > 0)) {

                                                                    // 5%
                                                                    var newTime = Math.min(player.currentTime + player.options.defaultSeekForwardInterval(player, media), (player.options.duration > 0) ? player.options.duration : media.duration);
                                                                    player.setCurrentTime(newTime);
                                                    }
                                    }
				},
                                {
                                    keys: [77], // M
                                    action: function(player, media) {
                                        player.container.find('.mejs-volume-slider').css('display','block');
                                        if (player.media.muted) {
                                            player.setMuted(false);
                                        } else {
                                            player.setMuted(true);
                                        }
                                    }
				}
		]
	};

	mejs.mepIndex = 0;

	mejs.players = {};

	// Wraps a MediaElement object in player controls
	mejs.MediaElementPlayer = function(node, o) {

                if ( !(this instanceof mejs.MediaElementPlayer) ) {
			return new mejs.MediaElementPlayer(node, o);
		}

		var t = this;

		// These will be reset after the MediaElement.success fires
		t.$media = t.$node = $(node);
		t.node = t.media = t.$media[0];

		// Check for existing player
		if (typeof t.node.player != 'undefined') {
			return t.node.player;
		} else {
			// Attach player to DOM node for reference
			t.node.player = t;
		}


		// Try to get options from data-mejsoptions
		if (typeof o == 'undefined') {
			o = t.$node.data('mejsoptions');
		}

		// Extend default options
		t.options = $.extend({},mejs.MepDefaults,o);

		// Unique ID
		t.id = 'mep_' + mejs.mepIndex++;

		// Add to player array
		mejs.players[t.id] = t;

		// Start
		t.init();

		return t;
	};

	// Actual player
	mejs.MediaElementPlayer.prototype = {

		hasFocus: false,

		controlsAreVisible: true,

		init: function() {

			var
				t = this,
				mf = mejs.MediaFeatures,
				// Options for MediaElement (shim)
				meOptions = $.extend(true, {}, t.options, {
					success: function(media, domNode) { t.meReady(media, domNode); },
					error: function(e) { t.handleError(e);}
				}),
				tagName = t.media.tagName.toLowerCase();

			t.isDynamic = tagName !== 'audio';

                        // Remove native controls
                        t.$media.removeAttr('controls');

                        // Build container
                        t.container =
                                $('<div id="' + t.id + '" class="mejs-container ' + (mejs.MediaFeatures.svg ? 'svg' : 'no-svg') + '">'+
                                        '<div class="mejs-inner">'+
                                                '<div class="mejs-mediaelement"></div>'+
                                                '<div class="mejs-layers"></div>'+
                                                '<div class="mejs-controls"></div>'+
                                                '<div class="mejs-clear"></div>'+
                                        '</div>' +
                                '</div>')
                                .addClass(t.$media[0].className)
                                .insertBefore(t.$media);

                        // Add classes for user and content
                        t.container.addClass(
                                (mf.isAndroid ? 'mejs-android ' : '') +
                                (mf.isiOS ? 'mejs-ios ' : '') +
                                (mf.isiPad ? 'mejs-ipad ' : '') +
                                (mf.isiPhone ? 'mejs-iphone ' : '') +
                                ('mejs-audio ')
                        );


                        // Move the <audio> tag into the right spot
                        if (mf.isiOS) {

                                // Sadly, you can't move nodes in iOS, so we have to destroy and recreate it!
                                var $newMedia = t.$media.clone();

                                t.container.find('.mejs-mediaelement').append($newMedia);

                                t.$media.remove();
                                t.$node = t.$media = $newMedia;
                                t.node = t.media = $newMedia[0]

                        } else {

                                // Normal way of moving it into place (doesn't work on iOS)
                                t.container.find('.mejs-mediaelement').append(t.$media);
                        }

                        // Find parts
                        t.controls = t.container.find('.mejs-controls');
                        t.layers = t.container.find('.mejs-layers');
                        
                        // Determine the size

                        if (t.options.width > 0 || t.options.width.toString().indexOf('%') > -1) {
                                t.width = t.options.width;
                        } else if (t.media.style.width !== '' && t.media.style.width !== null) {
                                t.width = t.media.style.width;
                        } else if (t.media.getAttribute('width') !== null) {
                                t.width = t.$media.attr('width');
                        } else {
                                t.width = t.options.defaultWidth;
                        }

                        if (t.options.height > 0 || t.options.height.toString().indexOf('%') > -1) {
                                t.height = t.options.height;
                        } else if (t.media.style.height !== '' && t.media.style.height !== null) {
                                t.height = t.media.style.height;
                        } else if (t.$media[0].getAttribute('height') !== null) {
                                t.height = t.$media.attr('height');
                        } else {
                                t.height = t.options.defaultHeight;
                        }

                        // Set the size, while we wait for the plugins to load below
                        t.setPlayerSize(t.width, t.height);

			// create MediaElement shim
			mejs.MediaElement(t.$media[0], meOptions);

			if (typeof(t.container) != 'undefined' && t.controlsAreVisible){
			    // Controls are shown when loaded
			    t.container.trigger('controlsshown');
			}
		},
                        
		showControls: function(doAnimation) {
			var t = this;

			doAnimation = typeof doAnimation == 'undefined' || doAnimation;

			if (t.controlsAreVisible)
				return;

			if (doAnimation) {
				t.controls
					.css('visibility','visible')
					.stop(true, true).fadeIn(200, function() {
					      t.controlsAreVisible = true;
					      t.container.trigger('controlsshown');
					});

				// Any additional controls people might add and want to hide
				t.container.find('.mejs-control')
					.css('visibility','visible')
					.stop(true, true).fadeIn(200, function() {t.controlsAreVisible = true;});

			} else {
				t.controls
					.css('visibility','visible')
					.css('display','block');

				// Any additional controls people might add and want to hide
				t.container.find('.mejs-control')
					.css('visibility','visible')
					.css('display','block');

				t.controlsAreVisible = true;
				t.container.trigger('controlsshown');
			}

			t.setControlsSize();

		},

		controlsEnabled: true,

		disableControls: function() {
			var t= this;

			this.controlsEnabled = false;
		},

		enableControls: function() {
			var t= this;

			t.showControls(false);

			t.controlsEnabled = true;
		},


		// Sets up all controls and events
		meReady: function(media, domNode) {


			var t = this,
				mf = mejs.MediaFeatures,
				autoplayAttr = domNode.getAttribute('autoplay'),
				autoplay = !(typeof autoplayAttr == 'undefined' || autoplayAttr === null || autoplayAttr === 'false'),
				featureIndex,
				feature;

			// Make sure it can't create itself again if a plugin reloads
			if (t.created) {
				return;
			} else {
				t.created = true;
			}

			t.media = media;
			t.domNode = domNode;

                        t.buildkeyboard(t, t.controls, t.layers, t.media);

                        // Add user-defined features/controls
                        for (featureIndex in t.options.features) {
                                feature = t.options.features[featureIndex];
                                if (t['build' + feature]) {
                                        try {
                                                t['build' + feature](t, t.controls, t.layers, t.media);
                                        } catch (e) {

                                        }
                                }
                        }

                        t.container.trigger('controlsready');

                        // Reset all layers and controls
                        t.setPlayerSize(t.width, t.height);
                        t.setControlsSize();

                        // EVENTS

                        // FOCUS: When a player starts playing, it takes focus from other players (possibily pausing them)
                        media.addEventListener('play', function() {
                                var playerIndex;

                                // Go through all other players
                                for (playerIndex in mejs.players) {
                                        var p = mejs.players[playerIndex];
                                        if (p.id != t.id && t.options.pauseOtherPlayers && !p.paused && !p.ended) {
                                                p.pause();
                                        }
                                        p.hasFocus = false;
                                }

                                t.hasFocus = true;
                        },false);


                        // Ended for all
                        t.media.addEventListener('ended', function (e) {

                                t.media.pause();

                                if (t.setCurrentRail) {
                                        t.setCurrentRail();
                                }
                                
                        }, false);

                        // Resize on the first play
                        t.media.addEventListener('loadedmetadata', function(e) {
                                if (t.updateDuration) {
                                        t.updateDuration();
                                }
                                if (t.updateCurrent) {
                                        t.updateCurrent();
                                }

                        }, false);


                        // Webkit has trouble doing this without a delay
                        setTimeout(function () {
                                t.setPlayerSize(t.width, t.height);
                                t.setControlsSize();
                        }, 50);

                        // Adjust controls whenever window sizes.
                        t.globalBind('resize', function() {

                                // Adjust controls
                                t.setControlsSize();
                        });

			// Force autoplay for HTML5
			if (autoplay && media.pluginType == 'native') {
				t.play();
			}


			if (t.options.success) {

				if (typeof t.options.success == 'string') {
					window[t.options.success](t.media, t.domNode, t);
				} else {
					t.options.success(t.media, t.domNode, t);
				}
			}
		},

		handleError: function(e) {
			var t = this;

			t.controls.hide();

			// Tell user that the file cannot be played
			if (t.options.error) {
				t.options.error(e);
			}
		},

		setPlayerSize: function(width,height) {
			var t = this;

			if (typeof width != 'undefined') {
				t.width = width;
			}

			if (typeof height != 'undefined') {
				t.height = height;
			}

			// Detect 100% mode - use currentStyle for IE since css() doesn't return percentages
                        if (t.height.toString().indexOf('%') > 0 || t.$node.css('max-width') === '100%' || parseInt(t.$node.css('max-width').replace(/px/,''), 10) / t.$node.offsetParent().width() === 1 || (t.$node[0].currentStyle && t.$node[0].currentStyle.maxWidth === '100%')) {

				// Do we have the native dimensions yet?
				var
					nativeWidth = t.options.defaultWidth,
					nativeHeight = t.options.defaultHeight;

				if (t.container.parent()[0].tagName.toLowerCase() === 'body') {
					nativeWidth = $(window).width();
					nativeHeight = $(window).height();
				}

				if ( nativeHeight != 0 && nativeWidth != 0 ) {
					// Set outer container size
					t.container
						.width(nativeWidth)
						.height(nativeHeight);

					// Set native <audio> and shims
					t.$media.add(t.container.find('.mejs-shim'))
						.width('100%')
						.height('100%');

					// Set the layers
					t.layers.children('.mejs-layer')
						.width('100%')
						.height('100%');
				}


			} else {

				t.container
					.width(t.width)
					.height(t.height);

				t.layers.children('.mejs-layer')
					.width(t.width)
					.height(t.height);

			}
		},

		setControlsSize: function() {
			var t = this,
				usedWidth = 0,
				railWidth = 0,
				rail = t.controls.find('.mejs-time-rail'),
				total = t.controls.find('.mejs-time-total'),
				current = t.controls.find('.mejs-time-current'),
				loaded = t.controls.find('.mejs-time-loaded'),
				others = rail.siblings();


			// Allow the size to come from custom CSS
			if (t.options && !t.options.autosizeProgress) {
				railWidth = parseInt(rail.css('width'));
			}

			// Attempt to autosize
			if (railWidth === 0 || !railWidth) {

				// Find the size of all the other controls besides the rail
				others.each(function() {
					var $this = $(this);
					if ($this.css('position') != 'absolute' && $this.is(':visible')) {
						usedWidth += $(this).outerWidth(true);
					}
				});

				// Fit the rail into the remaining space
				railWidth = t.controls.width() - usedWidth - (rail.outerWidth(true) - rail.width());
			}

			// Outer area
			rail.width(railWidth);
			// Dark space
			total.width(railWidth - (total.outerWidth(true) - total.width()));

			if (t.setCurrentRail)
				t.setCurrentRail();
		},

		buildkeyboard: function(player, controls, layers, media) {

				var t = this;

				// Listen for key presses
				t.globalBind('keydown', function(e) {

						if (player.hasFocus && player.options.enableKeyboard) {

								// Find a matching key
								for (var i=0, il=player.options.keyActions.length; i<il; i++) {
										var keyAction = player.options.keyActions[i];

										for (var j=0, jl=keyAction.keys.length; j<jl; j++) {
												if (e.keyCode == keyAction.keys[j]) {
														e.preventDefault();
														keyAction.action(player, media, e.keyCode);
														return false;
												}
										}
								}
						}

						return true;
				});

				// Check if someone clicked outside a player region, then kill its focus
				t.globalBind('click', function(event) {
						if ($(event.target).closest('.mejs-container').length == 0) {
								player.hasFocus = false;
						}
				});

		},
                        
		changeSkin: function(className) {
			this.container[0].className = 'mejs-container ' + className;
			this.setPlayerSize(this.width, this.height);
			this.setControlsSize();
		},
                        
		play: function()
                {
                    this.media.play();
		},
                        
		pause: function() {
			try {
				this.media.pause();
			} catch (e) {}
		},
                        
		load: function()
                {
                    this.media.load();
		},
                        
		setMuted: function(muted) {
			this.media.setMuted(muted);
		},
                        
		setCurrentTime: function(time) {
			this.media.setCurrentTime(time);
		},
                        
		getCurrentTime: function() {
			return this.media.currentTime;
		},
                        
		setVolume: function(volume) {
			this.media.setVolume(volume);
		},
                        
		getVolume: function() {
			return this.media.volume;
		},
                        
		setSrc: function(src) {
			this.media.setSrc(src);
		},
                        
		remove: function() {
			var t = this, featureIndex, feature;

			// Invoke features cleanup
			for (featureIndex in t.options.features) {
				feature = t.options.features[featureIndex];
				if (t['clean' + feature]) {
					try {
						t['clean' + feature](t);
					} catch (e) {
                                            
					}
				}
			}

			// Grab audio element and put it back in place
			if (!t.isDynamic) {
				t.$media.prop('controls', true);
				t.$node.clone().show().insertBefore(t.container);
				t.$node.remove();
			} else {
				t.$node.insertBefore(t.container);
			}

			if (t.media.pluginType !== 'native') {
				t.media.remove();
			}

			// Remove the player from the mejs.players object so that pauseOtherPlayers doesn't blow up when trying to pause a non existance flash api.
			delete mejs.players[t.id];

			t.container.remove();
			t.globalUnbind();
			delete t.node.player;
		}
	};

	(function(){
		var rwindow = /^((after|before)print|(before)?unload|hashchange|message|o(ff|n)line|page(hide|show)|popstate|resize|storage)\b/;

		function splitEvents(events, id) {
			// Add player ID as an event namespace so it's easier to unbind them all later
			var ret = {d: [], w: []};
			$.each((events || '').split(' '), function(k, v){
				var eventname = v + '.' + id;
				if (eventname.indexOf('.') === 0) {
					ret.d.push(eventname);
					ret.w.push(eventname);
				}
				else {
					ret[rwindow.test(v) ? 'w' : 'd'].push(eventname);
				}
			});
			ret.d = ret.d.join(' ');
			ret.w = ret.w.join(' ');
			return ret;
		}

		mejs.MediaElementPlayer.prototype.globalBind = function(events, data, callback) {
			var t = this;
			events = splitEvents(events, t.id);
			if (events.d) $(document).bind(events.d, data, callback);
			if (events.w) $(window).bind(events.w, data, callback);
		};

		mejs.MediaElementPlayer.prototype.globalUnbind = function(events, callback) {
			var t = this;
			events = splitEvents(events, t.id);
			if (events.d) $(document).unbind(events.d, callback);
			if (events.w) $(window).unbind(events.w, callback);
		};
	})();

	// Turn into jQuery plugin
	if (typeof jQuery != 'undefined') {
		jQuery.fn.mediaelementplayer = function (options) {
			if (options === false) {
				this.each(function () {
					var player = jQuery(this).data('mediaelementplayer');
					if (player) {
						player.remove();
					}
					jQuery(this).removeData('mediaelementplayer');
				});
			}
			else {
				this.each(function () {
					jQuery(this).data('mediaelementplayer', new mejs.MediaElementPlayer(this, options));
				});
			}
			return this;
		};
	}

	$(document).ready(function() {
		// Auto enable using JSON attribute
		$('.mejs-player').mediaelementplayer();
	});

	// Push out to window
	window.MediaElementPlayer = mejs.MediaElementPlayer;

})(mejs.$);

(function($) {

	$.extend(mejs.MepDefaults, {
		playpauseText: 'Play/Pause'
	});

	// PLAY/PAUSE BUTTON
	$.extend(MediaElementPlayer.prototype, {
		buildplaypause: function(player, controls, layers, media) {
			var 
				t = this,
				play = 
				$('<div class="mejs-button mejs-playpause-button mejs-play" >' +
					'<button type="button" aria-controls="' + t.id + '" title="' + t.options.playpauseText + '" aria-label="' + t.options.playpauseText + '"></button>' +
				'</div>')
				.appendTo(controls)
				.click(function(e) {
					e.preventDefault();
				
					if (media.paused) {
						media.play();
					} else {
						media.pause();
					}
					
					return false;
				});

			media.addEventListener('play',function() {
				play.removeClass('mejs-play').addClass('mejs-pause');
			}, false);
                        
			media.addEventListener('playing',function() {
				play.removeClass('mejs-play').addClass('mejs-pause');
			}, false);

			media.addEventListener('pause',function() {
				play.removeClass('mejs-pause').addClass('mejs-play');
			}, false);
                        
			media.addEventListener('paused',function() {
				play.removeClass('mejs-pause').addClass('mejs-play');
			}, false);
		}
	});
	
})(mejs.$);

(function($) {
	// Progress Bar
	$.extend(MediaElementPlayer.prototype, {
		buildprogress: function(player, controls, layers, media) {

			$('<div class="mejs-time-rail">'+
				'<span class="mejs-time-total">'+
					'<span class="mejs-time-buffering"></span>'+
					'<span class="mejs-time-loaded"></span>'+
					'<span class="mejs-time-current"></span>'+
					'<span class="mejs-time-handle"></span>'+
					'<span class="mejs-time-float">' + 
						'<span class="mejs-time-float-current">00:00</span>' + 
						'<span class="mejs-time-float-corner"></span>' + 
					'</span>'+
				'</span>'+
			'</div>')
				.appendTo(controls);
				controls.find('.mejs-time-buffering').hide();

			var 
				t = this,
				total = controls.find('.mejs-time-total'),
				loaded  = controls.find('.mejs-time-loaded'),
				current  = controls.find('.mejs-time-current'),
				handle  = controls.find('.mejs-time-handle'),
				timefloat  = controls.find('.mejs-time-float'),
				timefloatcurrent  = controls.find('.mejs-time-float-current'),
				handleMouseMove = function (e) {
                                        // Mouse position relative to the object
                                        var x = e.pageX,
                                        offset = total.offset(),
                                        width = total.outerWidth(true),
                                        percentage = 0,
                                        newTime = 0,
                                        pos = 0;


					if (media.duration || t.options.duration) {
						if (x < offset.left) {
							x = offset.left;
						} else if (x > width + offset.left) {
							x = width + offset.left;
						}
						
						pos = x - offset.left;
						percentage = (pos / width);
                                                
                                                newTime = percentage * (t.options.duration ? t.options.duration : media.duration);

						// Seek to where the mouse is
						if (mouseIsDown && newTime !== t.currentTime) {
                                                        t.setCurrentTime(newTime);
                                                }

						// Position floating time box
						if (!mejs.MediaFeatures.hasTouch) {
								timefloat.css('left', pos);
								timefloatcurrent.html( mejs.Utility.secondsToTimeCode(newTime) );
								timefloat.show();
						}
					}
				},
				mouseIsDown = false,
				mouseIsOver = false;

			// Handle clicks
			total
				.bind('mousedown', function (e) {
                                    // Only handle left clicks
                                    if (e.which === 1 || e.which === 0) {
						mouseIsDown = true;
						handleMouseMove(e);
						t.globalBind('mousemove.dur', function(e) {
							handleMouseMove(e);
						});
						t.globalBind('mouseup.dur', function (e) {
							mouseIsDown = false;
							timefloat.hide();
							t.globalUnbind('.dur');
						});
						return false;
					}
				})
				.bind('mouseenter', function(e) {
					mouseIsOver = true;
					t.globalBind('mousemove.dur', function(e) {
						handleMouseMove(e);
					});
					if (!mejs.MediaFeatures.hasTouch) {
						timefloat.show();
					}
				})
				.bind('mouseleave',function(e) {
					mouseIsOver = false;
					if (!mouseIsDown) {
						t.globalUnbind('.dur');
						timefloat.hide();
					}
				});

			// Loading
			media.addEventListener('progress', function (e) {
				player.setProgressRail(e);
				player.setCurrentRail(e);
			}, false);

			// Current time
			media.addEventListener('timeupdate', function(e) {
				player.setProgressRail(e);
				player.setCurrentRail(e);
			}, false);
			
			
			// Store for later use
			t.loaded = loaded;
			t.total = total;
			t.current = current;
			t.handle = handle;
		},
		setProgressRail: function(e) {

			var
				t = this,
				target = (e != undefined) ? e.target : t.media,
				percent = null;			

			// newest HTML5 spec has buffered array (FF4, Webkit)
			if (target && target.buffered && target.buffered.length > 0 && target.buffered.end && target.duration) {
				// TODO: account for a real array with multiple values (only Firefox 4 has this so far) 
				percent = target.buffered.end(0) / target.duration;
			} 
			// Some browsers (e.g., FF3.6 and Safari 5) cannot calculate target.bufferered.end()
			// to be anything other than 0. If the byte count is available we use this instead.
			// Browsers that support the else if do not seem to have the bufferedBytes value and
			// should skip to there. Tested in Safari 5, Webkit head, FF3.6, Chrome 6, IE 7/8.
			else if (target && target.bytesTotal != undefined && target.bytesTotal > 0 && target.bufferedBytes != undefined) {
				percent = target.bufferedBytes / target.bytesTotal;
			}
			// Firefox 3 with an Ogg file seems to go this way
			else if (e && e.lengthComputable && e.total != 0) {
				percent = e.loaded/e.total;
			}

			// finally update the progress bar
			if (percent !== null) {
				percent = Math.min(1, Math.max(0, percent));
				// update loaded bar
				if (t.loaded && t.total) {
					t.loaded.width(t.total.width() * percent);
				}
			}
		},
		setCurrentRail: function() {

			var t = this;
		
                        if (t.currentTime && (t.options.duration > 0) || (t.media.duration > 0)) {
                            // Update bar
                            if (t.total && t.handle) {
                                    var 
                                            newWidth = Math.round(t.total.width() * t.currentTime / (t.options.duration ? t.options.duration : t.media.duration)),
                                            handlePos = newWidth - Math.round(t.handle.outerWidth(true) / 2);

                                    t.current.width(newWidth);
                                    t.handle.css('left', handlePos);
                            }
                        }

		}
	});
})(mejs.$);
// Source Chooser Plugin
(function($) {

	$.extend(mejs.MepDefaults, {
		sourcechooserText: 'Source Chooser'
	});

	$.extend(MediaElementPlayer.prototype, {
		buildsourcechooser: function(player, controls, layers, media) {

			var t = this;

			player.sourcechooserButton =
				$('<div class="mejs-button mejs-sourcechooser-button">'+
					'<button type="button" aria-controls="' + t.id + '" title="' + t.options.sourcechooserText + '" aria-label="' + t.options.sourcechooserText + '"></button>'+
					'<div class="mejs-sourcechooser-selector">'+
						'<ul>'+
						'</ul>'+
					'</div>'+
				'</div>')
					.appendTo(controls)

					// hover
					.hover(function() {
						$(this).find('.mejs-sourcechooser-selector').css('visibility','visible');
					}, function() {
						$(this).find('.mejs-sourcechooser-selector').css('visibility','hidden');
					})

					// handle clicks to the language radio buttons
					.delegate('input[type=radio]', 'click', function() {
						src = this.value;

						if (media.currentSrc != src) {
							currentTime = media.currentTime;
							paused = media.paused;
							media.setSrc(src);
							media.load();
							media.addEventListener('loadedmetadata', function(e){
				                this.currentTime = currentTime;
				            }, true);
				            media.addEventListener('canplay', function(e){
				            	if (!paused) {
					            	this.play();
					            }
				            }, true);
						}
					});

			// add to list
			for (i in media.children) {
				src = media.children[i];
				if (src.nodeName === 'SOURCE' && (media.canPlayType(src.type) == 'probably' || media.canPlayType(src.type) == 'maybe')) {
					player.addSourceButton(src.src, src.title, src.type, media.src == src.src);
				}
			}

		},

		addSourceButton: function(src, label, type, isCurrent) {
			var t = this;
			if (label === '' || label == undefined) {
				label = src;
			}
			type = type.split('/')[1];

			t.sourcechooserButton.find('ul').append(
				$('<li>'+
					'<input type="radio" name="' + t.id + '_sourcechooser" id="' + t.id + '_sourcechooser_' + label + type + '" value="' + src + '" ' + (isCurrent ? 'checked="checked"' : '') + ' />'+
					'<label for="' + t.id + '_sourcechooser_' + label + type + '">' + label + ' (' + type + ')</label>'+
				'</li>')
			);

			t.adjustSourcechooserBox();

		},

		adjustSourcechooserBox: function() {
			var t = this;
			// adjust the size of the outer box
			t.sourcechooserButton.find('.mejs-sourcechooser-selector').height(
				t.sourcechooserButton.find('.mejs-sourcechooser-selector ul').outerHeight(true)
			);
		}
	});

})(mejs.$);

(function($) {
	
	// Options
	$.extend(mejs.MepDefaults, {
		timeAndDurationSeparator: '<span> | </span>'
	});


	// Time
	$.extend(MediaElementPlayer.prototype, {
		buildcurrent: function(player, controls, layers, media) {
			var t = this;
			
			$('<div class="mejs-time">'+
					'<span class="mejs-currenttime">' + (player.options.alwaysShowHours ? '00:00:00' : '00:00')
					+ '</span>'+ '</div>')
					.appendTo(controls);
			
			t.currenttime = t.controls.find('.mejs-currenttime');

                            
                        media.addEventListener('timeupdate',function() {
                            player.updateCurrent();
                            player.currentTime = media.currentTime;

                        }, false);
                            
		},


		buildduration: function(player, controls, layers, media) {
			var t = this;
			
			if (controls.children().last().find('.mejs-currenttime').length > 0) {
				$(t.options.timeAndDurationSeparator +
					'<span class="mejs-duration">' + 
						(t.options.duration > 0 ? 
							mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600) :
				   			(player.options.alwaysShowHours ? '00:00:00' : '00:00') 
				   		) + 
					'</span>')
					.appendTo(controls.find('.mejs-time'));
			} else {

				// Add class to current time
				controls.find('.mejs-currenttime').parent().addClass('mejs-currenttime-container');
				
				$('<div class="mejs-time mejs-duration-container">'+
					'<span class="mejs-duration">' + 
						(t.options.duration > 0 ? 
							mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.options.duration > 3600) :
				   			(player.options.alwaysShowHours ? '00:00:00' : '00:00') 
				   		) + 
					'</span>' +
				'</div>')
				.appendTo(controls);
			}
			
			t.durationD = t.controls.find('.mejs-duration');

                        media.addEventListener('timeupdate',function() {
                            player.updateDuration();
                        }, false);
		},
		
		updateCurrent:  function() {
            
			var t = this;

			if (t.currenttime) {
                            t.currenttime.html(mejs.Utility.secondsToTimeCode(t.currentTime, t.options.alwaysShowHours || (t.options.duration ? t.options.duration > 3600 : t.media.duration > 3600)));
                        }
		},
		
		updateDuration: function() {   
			var t = this;

			//Toggle the long audio class if the audio is longer than an hour.
                        if(t.options.duration > 0)
                            t.container.toggleClass("mejs-long-audio", t.options.duration > 3600);
                        else
                            t.container.toggleClass("mejs-long-audio", t.media.duration > 3600);
			
			if (t.durationD && (t.options.duration > 0 || t.media.duration > 0)) {
				t.durationD.html(mejs.Utility.secondsToTimeCode((t.options.duration ? t.options.duration : t.media.duration), t.options.alwaysShowHours));
			}	
                }
	});

})(mejs.$);

(function($) {

	$.extend(mejs.MepDefaults, {
		muteText: 'Mute Toggle',
		hideVolumeOnTouchDevices: true,
	});

	$.extend(MediaElementPlayer.prototype, {
		buildvolume: function(player, controls, layers, media) {
				
			// Android and iOS don't support volume controls
			if (mejs.MediaFeatures.hasTouch && this.options.hideVolumeOnTouchDevices)
				return;
			
			var t = this,
				mode = t.options.audioVolume,
				mute =
				
				// Horizontal version
				$('<div class="mejs-button mejs-volume-button mejs-mute">'+
					'<button type="button" aria-controls="' + t.id + '" title="' + t.options.muteText + '" aria-label="' + t.options.muteText + '"></button>'+
				'</div>' +
				'<div class="mejs-horizontal-volume-slider">'+ // Outer background
					'<div class="mejs-horizontal-volume-total"></div>'+ // Line background
					'<div class="mejs-horizontal-volume-current"></div>'+ // Current volume
					'<div class="mejs-horizontal-volume-handle"></div>'+ // Handle
				'</div>'
				)
					.appendTo(controls),
			volumeSlider = t.container.find('.mejs-volume-slider, .mejs-horizontal-volume-slider'),
			volumeTotal = t.container.find('.mejs-volume-total, .mejs-horizontal-volume-total'),
			volumeCurrent = t.container.find('.mejs-volume-current, .mejs-horizontal-volume-current'),
			volumeHandle = t.container.find('.mejs-volume-handle, .mejs-horizontal-volume-handle'),

			positionVolumeHandle = function(volume, secondTry) {

				if (!volumeSlider.is(':visible') && typeof secondTry == 'undefined') {
					volumeSlider.show();
					positionVolumeHandle(volume, true);
					volumeSlider.hide()
					return;
				}
			
				// Correct to 0-1
				volume = Math.max(0,volume);
				volume = Math.min(volume,1);					
				
				// Adjust mute button style
				if (volume == 0) {
					mute.removeClass('mejs-mute').addClass('mejs-unmute');
				} else {
					mute.removeClass('mejs-unmute').addClass('mejs-mute');
				}				

				// Position slider 
				if (mode == 'vertical') {
                                    
					var 
					
                                        // Height of the full size volume slider background
                                        totalHeight = volumeTotal.height(),

                                        // Top/left of full size volume slider background
                                        totalPosition = volumeTotal.position(),

                                        // The new top position based on the current volume
                                        newTop = totalHeight - (totalHeight * volume);
	
					// Handle
					volumeHandle.css('top', Math.round(totalPosition.top + newTop - (volumeHandle.height() / 2)));
	
					// Show the current visibility
					volumeCurrent.height(totalHeight - newTop );
					volumeCurrent.css('top', totalPosition.top + newTop);
				} else {
                                    
					var 
					
                                        // Height of the full size volume slider background
                                        totalWidth = volumeTotal.width(),

                                        // Top/left of full size volume slider background
                                        totalPosition = volumeTotal.position(),

                                        // The new left position based on the current volume
                                        newLeft = totalWidth * volume;
	
					// Handle
					volumeHandle.css('left', Math.round(totalPosition.left + newLeft - (volumeHandle.width() / 2)));
	
					// Rezize the current part of the volume bar
					volumeCurrent.width( Math.round(newLeft) );
				}
			},
                                
			handleVolumeMove = function(e) {
				
				var volume = null,
					totalOffset = volumeTotal.offset();
				
				// Calculate the new volume based on the mouse position
				if (mode == 'vertical') {
				
					var
                                        
                                        railHeight = volumeTotal.height(),
                                        totalTop = parseInt(volumeTotal.css('top').replace(/px/,''),10),
                                        newY = e.pageY - totalOffset.top;
						
					volume = (railHeight - newY) / railHeight;
						
					// The controls hide themselves (usually when mouse moves too far up)
					if (totalOffset.top == 0 || totalOffset.left == 0)
						return;
					
				} else {
					var
                                        
                                        railWidth = volumeTotal.width(),
                                        newX = e.pageX - totalOffset.left;
						
					volume = newX / railWidth;
				}
				
				// Ensure the volume isn't outside 0-1
				volume = Math.max(0,volume);
				volume = Math.min(volume,1);
				
				// Position the slider and handle			
				positionVolumeHandle(volume);
				
				// Set the media object (this will trigger the volumechanged event)
				if (volume == 0) {
					media.setMuted(true);
				} else {
					media.setMuted(false);
				}
				media.setVolume(volume);			
			},
			mouseIsDown = false,
			mouseIsOver = false;

			// SLIDER
			
			mute
				.hover(function() {
					volumeSlider.show();
					mouseIsOver = true;
				}, function() {
					mouseIsOver = false;	
						
					if (!mouseIsDown && mode == 'vertical')	{
						volumeSlider.hide();
					}
				});
			
			volumeSlider
				.bind('mouseover', function() {
					mouseIsOver = true;	
				})
				.bind('mousedown', function (e) {
					handleVolumeMove(e);
					t.globalBind('mousemove.vol', function(e) {
						handleVolumeMove(e);
					});
					t.globalBind('mouseup.vol', function () {
						mouseIsDown = false;
						t.globalUnbind('.vol');

						if (!mouseIsOver && mode == 'vertical') {
							volumeSlider.hide();
						}
					});
					mouseIsDown = true;
						
					return false;
				});


			// MUTE button
			mute.find('button').click(function() {
				media.setMuted( !media.muted );
			});

			// Listen for volume change events from other sources
			media.addEventListener('volumechange', function(e) {
				if (!mouseIsDown) {
					if (media.muted) {
						positionVolumeHandle(0);
						mute.removeClass('mejs-mute').addClass('mejs-unmute');
					} else {
						positionVolumeHandle(media.volume);
						mute.removeClass('mejs-unmute').addClass('mejs-mute');
					}
				}
			}, false);

			if (t.container.is(':visible')) {
				// Set initial volume
				positionVolumeHandle(player.options.startVolume);

				// Mutes the media and sets the volume icon muted if the initial volume is set to 0
                                if (player.options.startVolume === 0) {
                                  media.setMuted(true);
                                }

				// Shim gets the startvolume as a parameter, but we have to set it on the native <audio> elements
				if (media.pluginType === 'native') {
					media.setVolume(player.options.startVolume);
				}
			}
		}
	});
	
})(mejs.$);

/*
* ContextMenu Plugin
* 
*
*/

(function($) {

$.extend(mejs.MepDefaults,
	{ 'contextMenuItems': [
		// demo of a mute/unmute button
		{ 
			render: function(player) {
				if (player.media.muted) {
					return 'Unmute';
				} else {
					return 'Mute';
				}
			},
			click: function(player) {
				if (player.media.muted) {
					player.setMuted(false);
				} else {
					player.setMuted(true);
				}
			}
		},
		// separator
		{
			isSeparator: true
		}
		,
		// demo of simple download
		{ 
			render: function(player) {
				return 'Download File';
			},
			click: function(player) {
				window.location.href = player.media.currentSrc;
			}
		}	
	]}
);


	$.extend(MediaElementPlayer.prototype, {
		buildcontextmenu: function(player, controls, layers, media) {
			
			// create context menu
			player.contextMenu = $('<div class="mejs-contextmenu"></div>')
								.appendTo($('body'))
								.hide();
			
			// create events for showing context menu
			player.container.bind('contextmenu', function(e) {
				if (player.isContextMenuEnabled) {
					e.preventDefault();
					player.renderContextMenu(e.clientX-1, e.clientY-1);
					return false;
				}
			});
			player.container.bind('click', function() {
				player.contextMenu.hide();
			});	
			player.contextMenu.bind('mouseleave', function() {

				//
				player.startContextMenuTimer();
				
			});		
		},

		cleancontextmenu: function(player) {
			player.contextMenu.remove();
		},
		
		isContextMenuEnabled: true,
		enableContextMenu: function() {
			this.isContextMenuEnabled = true;
		},
		disableContextMenu: function() {
			this.isContextMenuEnabled = false;
		},
		
		contextMenuTimeout: null,
		startContextMenuTimer: function() {
			//
			
			var t = this;
			
			t.killContextMenuTimer();
			
			t.contextMenuTimer = setTimeout(function() {
				t.hideContextMenu();
				t.killContextMenuTimer();
			}, 750);
		},
		killContextMenuTimer: function() {
			var timer = this.contextMenuTimer;
			
			//
			
			if (timer != null) {				
				clearTimeout(timer);
				delete timer;
				timer = null;
			}
		},		
		
		hideContextMenu: function() {
			this.contextMenu.hide();
		},
		
		renderContextMenu: function(x,y) {
			
			// alway re-render the items so that things like "turn fullscreen on" and "turn fullscreen off" are always written correctly
			var t = this,
				html = '',
				items = t.options.contextMenuItems;
			
			for (var i=0, il=items.length; i<il; i++) {
				
				if (items[i].isSeparator) {
					html += '<div class="mejs-contextmenu-separator"></div>';
				} else {
				
					var rendered = items[i].render(t);
				
					// render can return null if the item doesn't need to be used at the moment
					if (rendered != null) {
						html += '<div class="mejs-contextmenu-item" data-itemindex="' + i + '" id="element-' + (Math.random()*1000000) + '">' + rendered + '</div>';
					}
				}
			}
			
			// position and show the context menu
			t.contextMenu
				.empty()
				.append($(html))
				.css({top:y, left:x})
				.show();
				
			// bind events
			t.contextMenu.find('.mejs-contextmenu-item').each(function() {
							
				// which one is this?
				var $dom = $(this),
					itemIndex = parseInt( $dom.data('itemindex'), 10 ),
					item = t.options.contextMenuItems[itemIndex];
				
				// bind extra functionality?
				if (typeof item.show != 'undefined')
					item.show( $dom , t);
				
				// bind click action
				$dom.click(function() {			
					// perform click action
					if (typeof item.click != 'undefined')
						item.click(t);
					
					// close
					t.contextMenu.hide();				
				});				
			});			
		}
	});
	
})(mejs.$);

